package com.cooge.collection.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class NetUtil {
	
	public static void GetDownloadFile(String url,String savePath,BufferSync bufferSync){
		
		HttpClient httpClient = new HttpClient();
		

		InputStream  in = null;
		OutputStream os = null;
		System.out.println(url);
		 try {
			url = url.replaceAll(" ","%");
			
			GetMethod getMethod = new GetMethod(url);
			int statusCode = httpClient.executeMethod(getMethod);
			
			bufferSync.downStatus(String.valueOf(statusCode));
			
		    in = getMethod.getResponseBodyAsStream();
		    
			int tsize = in.available();
			if(tsize==0){
				
				tsize =(int)getMethod.getResponseContentLength();
			}
			int p =0 ;
			int i = 0;
			
			File file = new File(savePath);
			String path = file.getCanonicalPath();
			
			System.out.println(path);
			
			File f= new File(path.substring(0,path.lastIndexOf("\\")));
			if(!f.isDirectory()){
				f.mkdirs();
			}
			
			System.out.println(url+":"+tsize);
			os = new FileOutputStream(file);
			byte b[] = new byte[1024];
			int len = 0;
			while((len=in.read(b,0,b.length))!=-1){
				
				if(tsize>0){
					p=p+b.length;
					i  = p*100/tsize;
					bufferSync.downProcess(i);
				}

				os.write(b,0,len);
			}
			in.close();
			os.close();
			bufferSync.finish();
		} catch (Exception e) {
			e.printStackTrace();
			if(in!=null)
				try {
					in.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			if(os!=null)
				try {
					os.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			
		} 
		
		
	}

}
